from helpers import updateInfo
import datetime
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ View popular keywords by categories class """
    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        # In first viewing of the page, display the categories list
        if (self.request.get('action')!="updateCategory"):
            select_options=""
            q_1 = db.GqlQuery("SELECT * FROM StocksCategories ORDER BY category")
            # Init prevCat (category name will never be empty)
            for p in q_1:
                    select_options+="<option>" + p.category + "</option>\n"
            
            template_values = {
                'current_user_totalamount': current_user.totalamount,
                'current_user_bankamount': current_user.bankamount,
                'current_user_investamount': current_user.totalamount-current_user.bankamount,
                'logusername' : user.nickname().capitalize(),
                'loginurl' : users.create_logout_url("/"),
                'logintext' : 'Sign Out',
                'select_options': select_options,
                'categoryName' : 'View Categories %s' % updateInfo.createToolTip("category"),
                'setHead' : 1,
                'headContent' : 'categories_main_head.html',
                'maincontent' : 'account_main.html',
                'account_main_content' : 'categories_main.html'
                
            }
            path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
            self.response.out.write(template.render(path, template_values))

        # After form submittion, show the categories results
        else:
                table_of_stocks_category=""
                
                q_1 = db.GqlQuery("SELECT * FROM StocksCategories " +
                "WHERE category = :1", self.request.get('categorytext'))
                if q_1.count()==0:
                    self.response.out.write("<div class=\"error-msg\">The Category you selected do not exsist</div>")
                else:
                    q_2 = db.GqlQuery("SELECT * FROM Stocks " +
                    "WHERE categoryref = :1 AND basketref= null ORDER BY userPrecentChange DESC", q_1[0])
                    
                    StockList = []
                    StockListNames = []
                    counter=0
                    for stock in q_2:
                        if stock.stockref==None:
                            continue
                        # Legendary (before Yahoo use)
                        #if stock.buydate.strftime("%Y-%m-%d")==datetime.datetime.now().strftime("%Y-%m-%d"):
                            #continue
                        if StockListNames.count(stock.stockref.stockname)==0:
                            StockList.append(stock)
                            StockListNames.append(stock.stockref.stockname)
                            counter+=1
    
                        if counter==20:
                            break
                        
                    # Updating table
                    
                    isData=1
                    if len(StockList)==0:
                        isData=0
                    table_of_stocks_category="\ndata.addRows(%d);\n" % len(StockList)
                    i=0
                    for stock in StockList:
                        if stock.stockref!=None:
                            stocknameLink='<a href="/trendProfile?TKey=%s" style="color:#3366CC">%s</a>' % (str(stock.stockref.key()),stock.stockref.stockname)
                        else:
                            stocknameLink='%s' % stock.stockref.stockname
                        buyDate=stock.buydate.strftime("%Y-%m-%d")
                        printPercentage, fontColor, changeSign= updateInfo.getPerInfo(stock.userPrecentChange)
                        table_of_stocks_category+="data.setCell(%d, 0, '%s');\n" % (i, stocknameLink)
                        table_of_stocks_category+="data.setCell(%d, 1, %s,'%s');\n" % (i,buyDate.replace('-',''), buyDate)
                        table_of_stocks_category+="data.setCell(%d, 2, %.2f,'(%s%.2f)',{style: 'color:%s;'});\n" % (i,stock.userPrecentChange, changeSign,printPercentage,fontColor)
                        table_of_stocks_category+="data.setCell(%d, 3, '%s');\n" % (i, stock.buyer)
                        i=i+1
                
                template_values = {
                    'current_user_totalamount': current_user.totalamount,
                    'current_user_bankamount': current_user.bankamount,
                    'current_user_investamount': current_user.totalamount-current_user.bankamount,
                    'logusername' : user.nickname().capitalize(),
                    'loginurl' : users.create_logout_url("/"),
                    'logintext' : 'Sign Out',
                    'categoryName' : 'View Categories',
                    'isData' : isData,
                    'table_of_stocks_category': table_of_stocks_category,
                    'categoryDisplay':self.request.get('categorytext'),
                    'setHead' : 1,
                    'headContent' : 'categories_head.html',
                    'maincontent' : 'account_main.html',
                    'account_main_content' : 'categories_results.html'
                }
                path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
                self.response.out.write(template.render(path, template_values))
            

            
application = webapp.WSGIApplication(
                                     [('/categories', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
